import socket
import threading
import find_mxnet
import mxnet as mx
import logging
import numpy as np
import model_predict

class myThread (threading.Thread):
    def __init__(self, clientsocket):
        threading.Thread.__init__(self)
        self.clientsocket = clientsocket
    def run(self):
        #self.clientsocket.settimeout(10)
        data = ""
        try:
            while True:
                line = self.clientsocket.recv(1024)
                data += line
                if line.endswith("#"):
                    break
        except socket.timeout:
            print "time out"
        json_str = data[0:-1]
        print "recv from client: " + json_str

        label = model_predict.predict(json_str)
        self.clientsocket.send(label)

        self.clientsocket.close()

def singleThread():
    print "[singleThread]"
    ip = socket.gethostbyname(socket.getfqdn())
    print ip
    host = ip
    port = 23459
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((host, port))
    sock.listen(1000)
    print "Server is running on port %d" % port
    while True:
        clientsocket, address = sock.accept()
        # print "accept client: " + str(address)
        data = ""
        try:
            while True:
                line = clientsocket.recv(1024)
                data += line
                if line.endswith("#"):
                    break
        except socket.timeout:
            print "time out"
        json_str = data[0:-1]
        print "recv from client: " + json_str

        label = model_predict.predict(json_str)
        clientsocket.send(label)

        clientsocket.close()

def multiThread():
    print "[multithread]"
    ip = socket.gethostbyname(socket.getfqdn())
    print ip
    host = ip
    port = 23459
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((host, port))
    sock.listen(1000)
    print "Server is running on port %d" % port
    while True:
        clientsocket, address = sock.accept()
        # print "accept client: " + str(address)
        t = myThread(clientsocket)
        t.start()

if __name__ == '__main__':
    multiThread()
    #singleThread()

